package com.ruoyi.base.permission;

import com.ruoyi.base.constant.Constants;
import com.ruoyi.base.enums.ExceptionEnum;
import com.ruoyi.base.exception.SysException;
import com.ruoyi.base.redis.login.LoginRedis;
import com.ruoyi.base.utils.servlet.ServletUtils;
import com.ruoyi.base.utils.uuid.UuidUtils;
import com.ruoyi.platform.system.user.dao.UserDAO;
import com.ruoyi.platform.system.user.pojo.LoginUserDTO;
import com.ruoyi.platform.system.user.pojo.UserDO;
import com.ruoyi.platform.system.user.pojo.UserDTO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenManager {
    //token刷新时间间隔阈值
    private static final Long MILLIS_MINUTE_TEN = 30 * 60 * 1000L;
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;
    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;
    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;
    @Autowired
    private UserDAO userDAO;
    @Autowired
    public StringRedisTemplate redisTemplate;
    @Autowired
    private LoginRedis loginRedis;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUserDTO getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            Claims claims = parseToken(token);
            if (claims == null) {
                throw new SysException(ExceptionEnum.NOT_LOGIN);
            }

            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            String userKey = getTokenKey(uuid);
            LoginUserDTO loginUser = loginRedis.getLoginUser(userKey);
            if (loginUser != null) {
                //判断最后一次登陆的uuid是否与本次uuid一致，不一致则证明当前账号被顶下来了
                String lastUuid = redisTemplate.boundValueOps(getUserIdKey(loginUser.getUser().getUserId())).get();
                if (!Objects.equals(uuid, lastUuid)) {
                    loginRedis.delCache(userKey);
                    throw new SysException(ExceptionEnum.NOT_LOGIN);
                }

                return loginUser;
            }
        }

        throw new SysException(ExceptionEnum.NOT_LOGIN);
    }

    /**
     * 获取后台登陆用户
     */
    public LoginUserDTO getLoginUser() {
        LoginUserDTO loginUser = getLoginUser(ServletUtils.getRequest());
        return Optional.ofNullable(loginUser).orElseThrow(() -> new SysException(ExceptionEnum.USER_NOT_EXIST));
    }

    /**
     * 获取后台登陆用户id
     */
    public long getLoginUserId() {
        return getLoginUser().getUser().getUserId();
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            loginRedis.delCache(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUserDTO loginUser) {
        String uuid = UuidUtils.getUuid();
        loginUser.setToken(uuid);
        //维护最后一次的uuid
        redisTemplate.boundValueOps(getUserIdKey(loginUser.getUser().getUserId())).set(uuid);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>(1);
        claims.put(Constants.LOGIN_USER_KEY, uuid);
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     */
    public void verifyToken(LoginUserDTO loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新缓存
     */
    public void refreshCache(long userId) {
        String lastUuid = redisTemplate.boundValueOps(getUserIdKey(userId)).get();
        if (StringUtils.isBlank(lastUuid)) {
            return;
        }

        LoginUserDTO loginUser = loginRedis.getLoginUser(getTokenKey(lastUuid));
        if (loginUser == null) {
            return;
        }

        UserDO user = userDAO.selectUserByPrimaryKey(userId);
        if (user == null) {
            loginRedis.delCache(getTokenKey(lastUuid));
            return;
        }

        loginUser.setUser(new UserDTO(user));
        refreshToken(loginUser);
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUserDTO loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * 60 * 1000);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        loginRedis.cache(userKey, loginUser, expireTime);
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception ignored) {
        }

        return null;
    }

    /**
     * 获取请求token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (token == null || "undefined".equalsIgnoreCase(token) || "null".equalsIgnoreCase(token)) {
            token = "";
        }
        return token;
    }

    private String getTokenKey(String uuid) {
        return Constants.LOGIN_TOKEN_KEY + uuid;
    }

    private String getUserIdKey(long userId) {
        return Constants.LOGIN_USER_ID + userId;
    }
}
